package com.fubowen.lepton.ui.container.children.bookmark

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.fubowen.lepton.R
import com.fubowen.lepton.bean.BookmarkBean
import com.fubowen.lepton.databinding.FragmentBookmarkEditBinding
import com.fubowen.lepton.helper.DBHelper
import com.fubowen.lepton.helper.ViewHelper.toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class BookmarkEditFragment : Fragment() {
    private lateinit var binding: FragmentBookmarkEditBinding
    private lateinit var controller: NavController
    private val args: BookmarkEditFragmentArgs by navArgs()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentBookmarkEditBinding.inflate(layoutInflater, container, false)
        controller = findNavController()
        goBack()
        binding.bookmarkEditTitle.apply {
            setText(args.title)
            requestFocus()
            val index = text.length
            setSelection(index)
        }
        binding.bookmarkEditUrl.setText(args.url)
        binding.bookmarkGroupBack.setOnClickListener { goBackImpl() }
        binding.bookmarkGroupSubmit.setOnClickListener {
            val title = binding.bookmarkEditTitle.text
            val url = binding.bookmarkEditUrl.text
            if (title.isNotBlank() && url.isNotBlank()) {
                submit(title.toString(), url.toString())
                goBackImpl()
            } else {
                binding.root.toast(R.string.bookmark_edit_error, 3000)
            }
        }
        return binding.root
    }

    private fun submit(title: String, url: String) {
        CoroutineScope(Dispatchers.Main).launch {
            DBHelper.db.bookmarkDao().put(
                BookmarkBean(
                    id = args.id,
                    title = title,
                    url = url,
                    parentId = args.parentId,
                )
            )
        }
    }

    private fun goBack() {
        val onBackCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                goBackImpl()
                isEnabled = false
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackCallback)
    }

    private fun goBackImpl() = controller.navigateUp()

}